package ru.bragnikita.utils.logexplorer.web;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Nikita.Brazhnikov
 */
public class ConvertationUtils {

	private static final long KB_SIZE = 1024;
	private static final long MB_SIZE = KB_SIZE * KB_SIZE;


	public static final String fileSizeFromBytesToString(Long o) {
		if (o == null)
			return "";
		if (o instanceof Long) {
			Long value = (Long) o;
			if (value < KB_SIZE)
				return value.toString() + " байт";
			if (value < MB_SIZE)
				return Long.valueOf(Math.round(value.doubleValue() / KB_SIZE)).toString() + " Кб";
			else
				return String.format("%3.2f Мб", value.doubleValue() / MB_SIZE);
		}
		return "";
	}

	private static final String[] DEFAILT_AVAILABLE_CHARSETS = {"UTF-8", "windows-1251", "windows-1252", "UTF-16", "US-ASCII", "IBM866"};

	public static String[] getAvailableCharsets() {
		return Arrays.copyOf(DEFAILT_AVAILABLE_CHARSETS, DEFAILT_AVAILABLE_CHARSETS.length);
	}

	private static final Map<String, String> MIME_MAP = new HashMap<String, String>();

	static {
		MIME_MAP.put("xml", "application/xml");
		MIME_MAP.put("html", "application/xml");
		MIME_MAP.put("xhtml", "application/xml");
		MIME_MAP.put("xhtml", "application/xml");
		MIME_MAP.put("java", "text/x-java");
		MIME_MAP.put("properties", "text/x-properties");
		MIME_MAP.put("css", "text/css");
		MIME_MAP.put("js", "text/javascript");
		MIME_MAP.put("sh", "text/x-rst");
	}

	public static String getAppropriateMimeType(String file) {
		final String extension = FilenameUtils.getExtension(file);
		if (StringUtils.isEmpty(extension))
			return "text/plain";
		String mime = MIME_MAP.get(extension);
		return mime != null ? mime : "text/ plain";
	}

	public static boolean isExecutable(String file) {
		final String extension = FilenameUtils.getExtension(file);
		if (StringUtils.isEmpty(extension))
			return false;
		return "bat".equals(extension);
	}
}
